<template>
  <div class="map">
    <div>位置信息</div>
    <div class="set" ref="map"></div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      ak: 'eESOIVn8ThSCqbEj0ZIMIScG',
      lng: '',
      lat: ''
    }
  },
  created () {
    this.lng = this.$route.query.lng
    console.log('精度', this.lng)
    this.lat = this.$route.query.lat
    console.log('维度', this.lat)
    const {getMapScript, initMap} = this
    getMapScript().then(initMap)
  },
  methods: {
    init (BMap) {
      let el = this.$refs.map
      console.log('el', el)
      const map = new BMap.Map(el)
      console.log('map', map)
      map.centerAndZoom(new BMap.Point(this.lng, this.lat), 16)
      // console.log(map.centerAndZoom(new BMap.Point(this.lng,this.lat),16))
      map.enableScrollWheelZoom(true)

      // 创建标注并将标注添加到地图中
      const newPoint = new BMap.Point(this.lng, this.lat)
      console.log('创建标注并将标注添加到地图中', newPoint)
      var marker = new BMap.Marker(newPoint)
      console.log('marker', marker)
      map.addOverlay(marker)
      map.panTo(newPoint)
    },
    initMap (BMap) {
      this.BMap = BMap
      console.log('bmap', this.BMap)
      this.init(BMap)
    },
    getMapScript () {
      if (!global.BMap) {
        global.BMap = {}
        global.BMap._preloader = new Promise((resolve, reject) => {
          global._initBaiduMap = function () {
            resolve(global.BMap)
            global.document.body.removeChild($script)
            global.BMap._preloader = null
            global._initBaiduMap = null
          }
          const $script = document.createElement('script')
          global.document.body.appendChild($script)
          $script.src = `//api.map.baidu.com/api?v=2.0&ak=${this.ak}&callback=_initBaiduMap`
        })
        return global.BMap._preloader
      } else if (!global.BMap._preloader) {
        return Promise.resolve(global.BMap)
      } else {
        return global.BMap._preloader
      }
    }
  }
}
</script>

<style scoped lang="less">
*{
  margin:0;
  padding:0
}
.map{
  font-size: .2rem;
  position: relative;
  top:1.5rem;
}
</style>
